from models.category import Category
from repository.categoryRepository import get_categories, get_category_by_id, create_category, update_category, delete_category, get_subcategories
from utils.response import JsonResponse
from fastapi import APIRouter

router = APIRouter()


@router.get("/listCategories", response_model=JsonResponse)
def read_categories():
    """获取系统中所有分类的完整列表"""
    # 获取所有分类信息
    categories = get_categories()
    return JsonResponse.success(categories)


@router.get("/getCategories/{category_id}", response_model=JsonResponse)
def read_category(category_id: int):
    """根据分类ID查询单个分类的详细信息

    Args:
        category_id (int): 分类的唯一标识ID，用于精准查询
    """
    # 根据ID获取分类信息
    db_category = get_category_by_id(category_id)
    if db_category is None:
        return JsonResponse.error("分类不存在", 404)
    return JsonResponse.success(db_category)


@router.post("/saveCateory", response_model=JsonResponse)
def create_new_category(category: Category):
    """创建新的分类信息

    Args:
        category (Category): 分类信息，包含名称、父级ID、层级和排序权重
    """
    # 创建分类
    db_category = create_category(category)
    return JsonResponse.success(db_category)


@router.put("/updateCateory/{category_id}", response_model=JsonResponse)
def update_existing_category(category_id: int, category: Category):
    """更新指定ID的分类信息，仅更新传递的字段

    Args:
        category_id (int): 要更新的分类ID，用于定位目标分类
        category (Category): 新的分类信息，包含名称、父级ID、层级和排序权重
    """
    # 更新分类
    db_category = update_category(category_id, category)
    if db_category is None:
        return JsonResponse.error("分类不存在", 404)
    return JsonResponse.success(db_category)


@router.delete("/delCateory/{category_id}", response_model=JsonResponse)
def delete_existing_category(category_id: int):
    """删除指定ID的分类信息

    Args:
        category_id (int): 要删除的分类ID，用于定位目标分类
    """
    # 删除分类
    success = delete_category(category_id)
    if not success:
        return JsonResponse.error("分类不存在", 404)
    return JsonResponse.success(None, "分类删除成功")


# 在文件末尾添加以下函数

@router.get("/{category_id}/subcategories", response_model=JsonResponse)
def read_subcategories(category_id: int):
    """根据父级分类ID查询子分类列表

    Args:
        category_id (int): 父级分类ID
    """
    # 根据父级ID获取子分类信息
    subcategories = get_subcategories(category_id)
    return JsonResponse.success(subcategories)